package com.yanqu.road.server.gameplayer.module.rank;

import com.yanqu.road.entity.player.UserRankValue;
import com.yanqu.road.logic.bussiness.player.UserRankValueBusiness;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wpj
 * @Date 2020/9/2
 */
public class RankValueModule extends GeneralModule {

    // 大类型 ,小类型
    Map<Integer, Map<Integer, UserRankValue>> rankValueMap;

    public Map<Integer, Map<Integer, UserRankValue>> getRankValueMap() {
        return rankValueMap;
    }

    public RankValueModule(GamePlayer player) {
        super(player);
    }

    public void setRankValue(int bigType, int childType, BigInteger value, String param) {
        try {
            if (!rankValueMap.containsKey(bigType)) {
                rankValueMap.put(bigType, new ConcurrentHashMap<>());
            }

            long time = System.currentTimeMillis();
            if (rankValueMap.get(bigType).get(childType) == null) {
                UserRankValue userRankValue = new UserRankValue();
                userRankValue.setUserId(player.getUserId());
                userRankValue.setType(bigType);
                userRankValue.setChildType(childType);
                userRankValue.setValue(value);
                userRankValue.setTime(time);
                userRankValue.setParam(param);
                userRankValue.setInsertOption();
                rankValueMap.get(bigType).put(childType, userRankValue);
            }

            UserRankValue userRankValue = rankValueMap.get(bigType).get(childType);
            userRankValue.setValue(value);
            userRankValue.setTime(time);
            userRankValue.setParam(param);

        } catch (Exception ex) {
            log.error(ex);
        }
    }

    @Override
    public boolean loadData() {
        rankValueMap = UserRankValueBusiness.getUserRankValueMap(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        for (Map<Integer, UserRankValue> map : rankValueMap.values()) {
            for (UserRankValue userRankValue : map.values()) {
                if (userRankValue.isInsertOption()) {
                    UserRankValueBusiness.addUserRankValue(userRankValue);
                } else if (userRankValue.isUpdateOption()) {
                    UserRankValueBusiness.updateUserRankValue(userRankValue);
                }
            }
        }
        return true;
    }
}
